import request from '../../utils/request'

Page({
  data: {
    id: 0,
    mainImageUrl: '',       // 主图URL
    subImages: [],          // 九宫格图片数据
    colorChange: 'changed',         // 颜色变化状态
    commodityId: 0,
    selectedSubImages: []   // 已选中的副图ID
  },

  onLoad() {
    this.loadCommodityAiImage();
  },

  loadCommodityAiImage(){


    request({
      url: 'commodity-ai-image',
      method: 'GET',
      data: { stage: 0},
    }).then(res => {
      const data = res.data
      this.setData({
          id: data.id,
          commodityId: data.commodityId,
          mainImageUrl: data.optimizedImage.url,
          subImages: data.imageList.map(item => ({
            id: item.id,
            image: item.image,
            selected: item.selected
          })),
          selectedSubImages: []
        });
    })
    .catch(err => {
      this.setData({ loading: false })
      wx.hideLoading()
      setTimeout(() => {
        wx.showToast({
          title: err.message || '请求失败',
          icon: 'none',
          duration: 3000
        })
      }, 100)
    })
  },

  // 九宫格图片选择
  toggleSelect(e) {
    const index = e.currentTarget.dataset.index;
    const newSubImages = [...this.data.subImages];
    const item = newSubImages[index];
    
    // 切换选中状态
    item.selected = !item.selected;
    
    // 更新选中ID列表
    const selectedIds = newSubImages
      .filter(img => img.selected)
      .map(img => img.id);
    
    // 控制台输出当前选中的副图ID
    console.log('当前选中的副图ID:', selectedIds);
    
    this.setData({
      subImages: newSubImages,
      selectedSubImages: selectedIds
    });
  },

  // 颜色变化单选
  selectColorChange(e) {
    this.setData({
      colorChange: e.currentTarget.dataset.value
    });
  },

  // 底部按钮操作
  handleAction(e) {
    const action = e.currentTarget.dataset.action;
    const params = {
      selectedIds: this.data.selectedSubImages,
      colorChange: this.data.colorChange,
      id: this.data.id
    };
    console.log(action)
    console.log(params)
    // 根据按钮类型执行不同操作
    const _this = this; // ✅ 保存 this 上下文

    switch(action) {
      case 'delete':
        wx.showModal({
          title: '确认删除',
          content: '确定要删除该商品素材吗？',
          confirmText: '删除',
          confirmColor: '#e64340', // 红色按钮
          cancelText: '取消',
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定');
              request({
                url: 'commodity-ai-image/review-first',
                method: 'POST',
                data: {
                  id: params.id,
                  actionType: 'DELETE',
                  subImageIds: params.selectedIds,
                  colorChange: params.colorChange === 'changed'
                }
              })
                .then(res => {
                    wx.showToast({
                      title: '删除成功',
                      icon: 'success'
                    });
        
                    // 可选：刷新数据
                     // ✅ 用 _this 调用原方法
                  _this.loadCommodityAiImage();
                  })
                .catch(err => {
                  wx.showToast({
                    title: err.message || '网络错误',
                    icon: 'none'
                  });
                });
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
        break;
      case 'reject':
        request({
          url: 'commodity-ai-image/review-first',
          method: 'POST',
          data: {
            id: params.id,
            actionType: 'INAPPROPRIATE',
            subImageIds: [],  // 不需要选图
            colorChange: params.colorChange === 'changed'
          }
        })
        .then(res => {
          wx.showToast({
            title: '提交成功',
            icon: 'success'
          });

          // 刷新数据或其他操作
          _this.loadCommodityAiImage();
        })
        .catch(err => {
          wx.showToast({ title: err.message || '网络错误', icon: 'none' });
        });
        break;
        // 此处调用API接口
        break;
      case 'approve':
        if (!params.selectedIds || params.selectedIds.length === 0) {
          wx.showToast({
            title: '请至少选择一张图片',
            icon: 'none'
          });
          return; // 不继续调用接口
        }
        request({
          url: 'commodity-ai-image/review-first',
          method: 'POST',
          data: {
            id: params.id,
            actionType: 'APPROPRIATE',
            subImageIds: params.selectedIds,
            colorChange: params.colorChange === 'changed'
          }
        })
        .then(res => {
          wx.showToast({
            title: '提交成功',
            icon: 'success'
          });

          _this.loadCommodityAiImage();
        })
        .catch(err => {
          wx.showToast({ title: err.message || '网络错误', icon: 'none' });
        });

        // 此处调用API接口
        break;
    }
    
    console.log('执行操作:', action, '参数:', params);
  },

  // 删除选中图片
  deleteSelectedImages() {
    const newSubImages = this.data.subImages.filter(
      item => !item.selected
    );
    
    this.setData({
      subImages: newSubImages,
      selectedSubImages: []
    });
    
    wx.showToast({ title: '已删除选中图片', icon: 'success' });
  },


  onPreviewImage(e) {
    const current = e.currentTarget.dataset.src
    if (!current) {
      wx.showToast({ title: '无效图片', icon: 'none' })
      return
    }
 
    const urls = [
      this.data.mainImageUrl,
      ...this.data.subImages.map(item => item.image.url)
    ]

    console.log(urls)
    wx.previewImage({
      current,
      urls
    })
  }
});